import { getUserInfo, updateUserInfo, wxLogin } from "@/api/user";
import utils from "@/utils/utils";
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useUserStore = defineStore("user", () => {
  const isLogin = ref(!uni.getStorageSync("token") ? false : true); // 是否登录
  const showLoginDialog = ref(false); // 是否显示登录弹窗
  const userInfo = ref({}); // 用户信息
  // 登录
  const login = async () => {
    try {
      const { code } = await uni.login();
      const res = await wxLogin({
        code,
        userId: uni.getStorageSync("inviteId") || "",
      });
      uni.setStorageSync("token", res.data.token);
      uni.setStorageSync("isUpdate", 1);
      uni.removeStorageSync("inviteId");
      isLogin.value = true;
      showLoginDialog.value = false;
      await getUserInfoReq();
      utils.showToast("登录成功");
    } catch (error) {}
  };
  const logout = () => {
    isLogin.value = false;
    uni.removeStorageSync("token");
    utils.useRouter("/pages/index/index", {}, "reLaunch");
    // uni.removeStorageSync("userInfo");
  };
  // 获取用户信息
  const getUserInfoReq = async () => {
    try {
      const res = await getUserInfo();
      userInfo.value = res.data;
      uni.setStorageSync("userInfo", res.data);
    } catch (error) {}
  };
  // 修改用户信息
  const updateUserInfoReq = async () => {
    try {
      const res = await updateUserInfo(userInfo.value);
      userInfo.value = res.data;
    } catch (error) {}
  };
  const pointTotal = computed(() => {
    return (
      Number(userInfo.value.appLevel?.pointTotal || 0) +
      Number(userInfo.value.appLevel?.pointNext || 0)
    );
  });
  return {
    isLogin,
    userInfo,
    login,
    logout,
    getUserInfoReq,
    updateUserInfoReq,
    showLoginDialog,
    pointTotal,
  };
});
